package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.constants.RedisConstant;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

//    @Resource
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public Result sendCode(String phone, HttpSession session) {
//        校验手机号
        if(RegexUtils.isPhoneInvalid(phone)){
//        如果不符合就返回错误信息
            return Result.fail("手机号格式错误");
        }
        String code = RandomUtil.randomNumbers(6);
//        符合就生成一个验证码
//        session.setAttribute("code", code);
        stringRedisTemplate.opsForValue().set( "login code" + phone, code, 50, TimeUnit.MINUTES);
//        然后将验证码保存到Session
        log.debug("发送短信验证码成功，验证码为{}", code);
//        返回值
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        log.info("当前执行到了login");
        String phone = loginForm.getPhone();
        if(RegexUtils.isPhoneInvalid(phone)){
            return Result.fail("手机号格式错误");
        }

        String cahceCode = stringRedisTemplate.opsForValue().get("login code" + phone);

        String code = loginForm.getCode();

        if (cahceCode == null || !cahceCode.equals(code)){
            return Result.fail("验证码错误");
        }

        User user =  query().eq("phone", phone).one();
        if(user == null){
            user = createUserWithPhone(phone);
        }

        String token = UUID.randomUUID().toString(true);

        UserDTO userDTO = new UserDTO();
        BeanUtil.copyProperties(user, userDTO);

        Map<String, Object> map = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create().setIgnoreNullValue(true)
                        .setFieldValueEditor((s, o) -> {
                            if (o == null) {
                                return null; // 如果原值为 null，编辑器返回 null
                            }
                            // 只有非 null 值才调用 toString()
                            return o.toString();}));
        log.info("login token + stringRedisTemplate.opsForHash().putAll");

        stringRedisTemplate.opsForHash().putAll(RedisConstant.LOGIN_TOKEN_KEY  + token, map);

        log.info("login token + stringRedisTemplate.opsForHash().putAll fished");

//        stringRedisTemplate.expire(RedisConstant.LOGIN_TOKEN_KEY + token, 30, TimeUnit.MINUTES);
//        session.setAttribute("user", user);
        return Result.ok(token);
    }

    private User createUserWithPhone(String phone) {

        User user = new User();
        user.setPhone(phone);
        user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));

        save(user);
        return null ;
    }
}
